<template>
  <bd-popup
    class="betInfoPopup"
    popupId="lotteryV3BetInfoPopup"
    :weights="4"
    :style="{
      'border-top-left-radius': '12px',
      'border-top-right-radius': '12px',
      width: '100vw',
    }"
    v-model:show="props.show"
    position="bottom"
    :z-index="999999"
    teleport="body"
    close-on-popstate
    safe-area-inset-bottom
    :close-on-click-overlay="false"
    :overlay-style="{ background: 'rgba(0, 0, 0, 0.5)' }"
    @click-overlay="popupClose"
    @click-close-icon="popupClose"
  >
    <van-swipe
      class="swipe"
      ref="swipeRef"
      :autoplay="999999999"
      :show-indicators="false"
      :loop="false"
      :touchable="false"
      @change="onChangeSwipe"
    >
      <!-- 下注 -->
      <van-swipe-item>
        <div class="box items-center">
          <!-- 标题 -->
          <div class="titlebg">
            <div class="titlebg-text">
              {{ $t("lotteryMoney.desc_title1_text11") }}
            </div>
            <img
              class="titlebg-close"
              @click="popupClose"
              src="/image/close-dark0-icon.svg"
            />
          </div>
          <!-- 内容 -->
          <div class="content items-center">
            <!-- 描述 -->
            <div class="content-title">{{ $t("lotteryMoney.djhmqkxg") }}</div>
            <!-- 号码列表 -->
            <div class="content-list items-center">
              <div
                v-for="(item, row) in numbers5"
                :key="item.id"
                class="content-list-item items-center"
                :class="{
                  'content-list-item-bm0': row + 1 == numbers5.length,
                }"
              >
                <!-- 序号 -->
                <div class="content-list-item-index">{{ row + 1 }}</div>
                <!-- 左边五个输入框 -->
                <div class="content-list-item-left items-center">
                  <div
                    v-for="(num, col) in item.numArr"
                    :key="col"
                    class="content-list-item-left-input"
                    :class="{
                      'content-list-item-left-input-activity':
                        `${row}${col}` == curSelectIndex,
                    }"
                    @click="clickNumItem(row, col)"
                  >
                    {{ num }}
                  </div>
                </div>
                <!-- 右边步进器 -->
                <van-stepper
                  class="content-list-item-right"
                  v-model="item.stepper"
                  min="0"
                  :max="item.stepMax"
                  integer
                  @blur="(val) => stepperBeforeBlur(row, val)"
                  :before-change="(val) => stepperBeforeChange(row, val)"
                />
              </div>
              <!-- 添加一组 -->
              <div
                v-if="numbers5.length < 5"
                class="content-add items-center"
                @click.stop="addNumber(1)"
              >
                <img
                  class="content-add-img"
                  src="/image/lottery-v3/add-group-icon.svg"
                />
                <div>{{ $t("lotteryMoney.addGroupNum") }}</div>
              </div>
            </div>
            <!-- 随机几组 -->
            <div class="content-random items-center">
              <div class="content-random-item" @click.stop="addNumber(1)">
                {{ $t("lotteryMoney.random1") }}
              </div>
              <div class="content-random-item" @click.stop="addNumber(3)">
                {{ $t("lotteryMoney.random3") }}
              </div>
              <div class="content-random-item" @click.stop="addNumber(5)">
                {{ $t("lotteryMoney.random5") }}
              </div>
            </div>
            <!-- 余额和剩余次数 -->
            <div class="content-bottom items-center">
              <!-- 余额 -->
              <div class="content-bottom-item items-center">
                <div class="content-bottom-item-title">
                  {{ $t("pledge.kyye") }}
                </div>
                <div class="content-bottom-item-value">
                  {{ toThousands(freeAmount) }}
                </div>
              </div>
              <div class="content-bottom-item-line"></div>
              <!-- 剩余次数 -->
              <div class="content-bottom-item items-center">
                <div class="content-bottom-item-title">
                  {{ $t("lotteryMoney.syxzcs") }}
                </div>
                <div class="content-bottom-item-value">
                  {{ lotteryStore.$state.leftDrawCount }}
                </div>
              </div>
              <div
                v-if="!!lotteryStore.$state.freeDrawCount"
                class="content-bottom-item-line"
              ></div>
              <!-- 免费次数 -->
              <div
                v-if="!!lotteryStore.$state.freeDrawCount"
                class="content-bottom-item items-center"
              >
                <div class="content-bottom-item-title">
                  {{ $t("lotteryMoney.mfxzcsText") }}
                </div>
                <div class="content-bottom-item-right items-center">
                  <img
                    class="content-bottom-item-right-icon"
                    src="/image/lottery-v3/invite-free-icon.svg"
                  />
                  <!-- <div class="content-bottom-item-value">*{{ needFrees }}</div> -->
                  <div class="content-bottom-item-value">
                    *{{ lotteryStore.$state.freeDrawCount }}
                  </div>
                  <!-- <div class="content-bottom-item-right-bdc">
                  -{{ needFrees * 100 }} BDC
                </div> -->
                </div>
              </div>
            </div>
          </div>
          <!-- 底部按钮 -->
          <div
            class="footer items-center"
            :class="{
              'footer-up': isKeyboardShow,
            }"
          >
            <div
              class="footer-btn"
              :class="{ 'footer-btn-disabled': isDisabled }"
              @click="confirm(1)"
            >
              {{ $t("lotteryMoney.ljxz") }}
            </div>
          </div>
        </div>
      </van-swipe-item>
      <!-- 结算 -->
      <van-swipe-item>
        <div class="box items-center">
          <!-- 标题 -->
          <div class="titleView items-center">
            <img
              class="titleView-close"
              @click="backStep"
              src="/image/left-arrow.png"
            />
            <div class="titleView-text">
              {{ $t("lotteryMoney.desc_title1_text11") }}
            </div>
            <img
              class="titleView-close"
              @click="popupClose"
              src="/image/close-dark0-icon.svg"
            />
          </div>
          <!-- 内容 -->
          <div class="content items-center">
            <!-- 描述 -->
            <div class="content-title">{{ $t("lotteryMoney.xzcgljkj") }}</div>
            <!-- 号码 -->
            <div class="content-settlements items-center">
              <div
                v-for="(item, row) in numbers5"
                :key="item.id"
                class="content-settlements-item items-center"
                :class="{
                  'content-settlements-item-bm0': row + 1 == numbers5.length,
                }"
              >
                <!-- 左边五个输入框 -->
                <div class="content-settlements-item-left items-center">
                  <!-- 序号 -->
                  <div class="content-settlements-item-index">
                    {{ row + 1 }}
                  </div>
                  <div
                    v-for="(num, col) in item.numArr"
                    :key="col"
                    class="content-settlements-item-left-input"
                    @click="clickNumItem(row, col)"
                  >
                    <img
                      class="content-settlements-item-left-input-bg"
                      src="/image/lottery-v3/num-zj-bg1.svg"
                    />
                    <div class="content-settlements-item-left-input-text">
                      {{ num }}
                    </div>
                  </div>
                </div>
                <!-- xx注 -->
                <div class="content-settlements-item-right">
                  *{{ item.stepper }}
                </div>
              </div>
            </div>
            <!-- 结算信息 -->
            <div class="content-bottom items-center">
              <!-- 下注数量 -->
              <div class="content-bottom-item items-center">
                <div class="content-bottom-item-title">
                  {{ $t("lotteryMoney.xzsls") }}
                </div>
                <div class="content-bottom-item-value">
                  {{ betTotal }} {{ $t("lotteryMoney.xxz") }}
                </div>
              </div>
              <div class="content-bottom-item-line"></div>
              <!-- 下注费用 -->
              <div class="content-bottom-item items-center">
                <div class="content-bottom-item-title">
                  {{ $t("lotteryMoney.xzfy") }}
                </div>
                <div class="content-bottom-item-value">
                  {{ toThousands(betTotal * 100) }} BDC
                </div>
              </div>
              <!-- 免费次数 -->
              <div
                v-if="!!lotteryStore.$state.freeDrawCount"
                class="content-bottom-item items-center"
              >
                <div class="content-bottom-item-title">
                  {{ $t("lotteryMoney.mfxzcsText") }}
                </div>
                <div class="content-bottom-item-right items-center">
                  <img
                    class="content-bottom-item-right-icon"
                    src="/image/lottery-v3/invite-free-icon.svg"
                  />
                  <div class="content-bottom-item-value">*{{ needFrees }}</div>
                  <div class="content-bottom-item-right-bdc">
                    -{{ needFrees * 100 }} BDC
                  </div>
                </div>
              </div>
            </div>
            <!-- 支付方式 + 需要支付 + 余额不足 -->
            <div class="content-footer items-center">
              <!-- 支付方式 -->
              <div class="content-settlements-method items-center">
                <!-- BDC -->
                <div
                  class="content-settlements-method-item items-center"
                  :class="{
                    'content-settlements-method-item-activity': costType == 1,
                    'content-settlements-method-item-disabled':
                      lotteryStore.$state.isFriDollarBet,
                  }"
                  @click.stop="costTypeChange(1)"
                >
                  <div
                    class="content-settlements-method-item-title"
                    :class="{
                      'content-settlements-method-item-title-activity':
                        costType == 1,
                    }"
                  >
                    BDC
                  </div>
                  <div
                    class="content-settlements-method-item-value"
                    :class="{
                      'content-settlements-method-item-value-activity':
                        costType == 1,
                    }"
                  >
                    {{ toThousands(freeAmount) }} BDC
                  </div>
                  <img
                    v-show="costType == 1"
                    class="content-settlements-method-item-icon"
                    src="/image/lottery-v3/settlement-method-icon.svg"
                  />
                </div>
                <!-- 避险账户 -->
                <div
                  class="content-settlements-method-item items-center"
                  :class="{
                    'content-settlements-method-item-activity': costType == 2,
                  }"
                  @click.stop="costTypeChange(2)"
                >
                  <div
                    class="content-settlements-method-item-title"
                    :class="{
                      'content-settlements-method-item-title-activity':
                        costType == 2,
                    }"
                  >
                    {{ $t("lotteryMoney.bxzhye").replace(":", "") }}
                  </div>
                  <div
                    class="content-settlements-method-item-value"
                    :class="{
                      'content-settlements-method-item-value-activity':
                        costType == 2,
                    }"
                  >
                    ${{ toThousands(accountBXInfo) }}
                  </div>
                  <img
                    v-show="costType == 2"
                    class="content-settlements-method-item-icon"
                    src="/image/lottery-v3/settlement-method-icon.svg"
                  />
                </div>
              </div>
              <!-- 需要支付 -->
              <div
                class="content-pay items-center"
                :class="{
                  'content-pay-bm0': isBxzhStatus == 3,
                }"
              >
                <span style="margin-right: 4px">{{
                  $t("lotteryMoney.xyzf")
                }}</span>
                <span class="content-pay-value">{{
                  costType == 2 ? "$" : ""
                }}</span>

                <span class="content-pay-value">{{
                  toThousands(
                    costType == 2 ? decimalToLength(needPay, 1) : needPay
                  )
                }}</span>
                <span class="content-pay-value">{{
                  costType == 1 ? "BDC" : ""
                }}</span>
              </div>
              <!-- 余额不足 -->
              <div
                v-if="isInsufficientPay"
                class="content-pay-yebz items-center"
              >
                <img class="content-pay-yebz-icon" src="/image/gth2.svg" />
                <div class="content-pay-yebz-text">
                  {{ $t("lottery.yebz") }}
                </div>
              </div>
            </div>
          </div>
          <!-- 底部按钮 -->
          <div class="footer items-center">
            <div
              class="footer-btn"
              :class="{ 'footer-btn-disabled': isDisabled }"
              @click="confirm(2)"
            >
              {{ $t("lotteryMoney.ljxz") }}
            </div>
          </div>
        </div>
      </van-swipe-item>
      <!-- 余额不足 / 激活避险账户 -->
      <van-swipe-item>
        <div class="box items-center">
          <div class="titlebg">
            <div class="titlebg-text"></div>
            <img
              class="titlebg-close"
              @click="popupClose"
              src="/image/close-dark0-icon.svg"
            />
          </div>
          <div class="content items-center">
            <!-- 去激活 -->
            <img
              v-if="isBxzhStatus == 0 || isBxzhStatus == 2"
              class="content-abnormal-img"
              src="/image/lotterymoney/betpopup-qjh-icon.svg"
            />
            <!-- 去充值 -->
            <img
              v-if="isBxzhStatus == 3"
              class="content-abnormal-img"
              src="/image/lotterymoney/betpopup-qcz-icon.svg"
            />
            <div class="content-abnormal-title">
              {{
                $t(
                  isBxzhStatus == 3
                    ? "lotteryMoney.bxzhyebz"
                    : "lotteryMoney.jhbxzh"
                ).split(", ")[0]
              }}
            </div>
            <div class="content-abnormal-desc">
              {{
                $t(
                  isBxzhStatus == 3
                    ? "lotteryMoney.bxzhyebz"
                    : "lotteryMoney.jhbxzh"
                ).split(", ")[1]
              }}
            </div>
          </div>
          <div class="footer items-center">
            <div class="footer-btn" @click="confirm(isBxzhStatus == 3 ? 3 : 4)">
              {{
                $t(isBxzhStatus == 3 ? "lotteryMoney.qcz" : "lotteryMoney.ljjh")
              }}
            </div>
          </div>
        </div>
      </van-swipe-item>
    </van-swipe>
    <!-- 自定义键盘 -->
    <transition name="van-slide-up">
      <div v-if="isKeyboardShow" class="keyboard">
        <div class="items-center keyboard-row0">
          <div
            class="keyboard-item"
            v-for="(item, index) in keyboardStrs[0]"
            :key="index"
            :class="{
              'keyboard-item-br0': index == 5,
            }"
            @click="keyboardClick(0, index)"
          >
            {{ item }}
          </div>
        </div>
        <div class="items-center keyboard-row1">
          <div
            class="keyboard-item"
            v-for="(item, index) in keyboardStrs[1]"
            :key="index"
            :class="{
              'keyboard-item-br0': index == 5,

              'keyboard-item-bt18': index > 5,
              'keyboard-item-confirm': index + 1 == keyboardStrs[1].length,
            }"
            @click="keyboardClick(1, index)"
          >
            {{ item }}
          </div>
        </div>
      </div>
    </transition>
  </bd-popup>
</template>
<script setup lang="ts" name="betInfoPopup">
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import { bettingBatchV3, getNewAccountInfo } from "@/api/lottery";
import { getUserAccount } from "@/api/user";
import * as MITO from "@zhj1214/qdjk-web";
import { useLotteryV3Store } from "~~/store/modules/lottery-v3";
import { useGlobalStore } from "~~/store/global";
import { useUserStore } from "~~/store/modules/user";
import { JUMPAPPS } from "~/config";
import Decimal from "decimal.js";

const { t } = useI18n();
const props = withDefaults(
  defineProps<{
    show: boolean;
    detail: any;
  }>(),
  {
    show: false,
    detail: {},
  }
);

const globalStore = useGlobalStore();
const lotteryStore = useLotteryV3Store();
const userStore = useUserStore();
const emit = defineEmits(["update:show", "call"]);
// firebase埋点
const firebase = useInitFirebase(); // 初始化firebase

/************************* start 获取账户信息 start *************************/
// 重试次数
let retrys = 3;
// 获取避险账户余额
const accountBXInfo = ref(Number(userStore.$state.savingsAccountBalance) || 0);
const isBxzhStatus = ref(userStore.$state.bxzhStatus); // 避险账户状态: 0: 未开通 1. 正常 2.没有启用避险账户 3. 余额不足
// 获取,避险账户信息
const getNewAccountInfoRequest = async () => {
  const res = await getNewAccountInfo();
  console.log("--避险账户:", res);
  if (res) {
    /**************** zhjdebugger ****************/
    // res.balance = 0.001;
    // res.status = 0;
    /**************** zhjdebugger ****************/
    accountBXInfo.value = Number(res.balance || 0);
    // res.status 账户状态 0 未开通、1 已开通(正常账户)
    if (res.status == 1) {
      // 是否启用避险账户功能: true 表示当前版本启用避险账户
      if (res.enabled) {
        isBxzhStatus.value = 1;
      } else {
        isBxzhStatus.value = 2;
      }
    } else {
      isBxzhStatus.value = 0;
    }
    userStore.$patch((state) => {
      state.savingsAccountBalance = res.balance || "";
      state.bxzhStatus = isBxzhStatus.value;
    });
  } else {
    if (retrys > 1) {
      retrys = retrys - 1;
      setTimeout(() => {
        getNewAccountInfoRequest();
      }, 1000);
    }

    MITO.log({
      message: "lottery V3 避险账户信息,获取失败",
      tag: "手动上报",
      level: "low",
      ex: "手动上报",
    });
  }
};

// 可用余额 BDC
const freeAmount = ref(userStore.$state.freeAmount || 0);
let accountStatus = 0; // != 1 代表账户异常(冻结)
// BDC 账户信息
const getUserAccountRequest = async () => {
  const res = await getUserAccount();
  if (res) {
    /**************** zhjdebugger ****************/
    // res.freeAmount = 90;
    /**************** zhjdebugger ****************/
    freeAmount.value = res.freeAmount;
    userStore.$patch((state) => {
      state.freeAmount = res.freeAmount;
    });
    accountStatus = res.accountStatus;
  } else {
    if (retrys > 1) {
      retrys = retrys - 1;
      setTimeout(() => {
        getUserAccountRequest();
      }, 1000);
    }
  }
};

/**************** swipe ****************/
const swipeRef = ref();
// 第几步骤: 0. 选择号码 1.确认下注 2.余额不足/激活避险账户
const step = ref(0);
// swipe 改变事件
const onChangeSwipe = (val: any) => {
  console.log("swipe 改变事件 ", val);
  step.value = val;
};
// 返回上一步骤
const backStep = () => {
  swipeRef.value && swipeRef.value?.prev();
};

// 余额不足
const isInsufficientPay = computed(() => {
  if (step.value == 1) {
    if (costType.value == 2) {
      return Number(needPay.value) > Number(accountBXInfo.value);
    } else if (costType.value == 1) {
      return Number(needPay.value) > Number(freeAmount.value);
    }
  }
  return false;
});

onMounted(() => {
  // 1. BDC 账户
  getUserAccountRequest();
  // 2. 获取避险账户余额
  getNewAccountInfoRequest();
  // 3. 先随机生成一组号码
  // addNumber(1);
  // 4. 无资格,只能美金下注逻辑
  if (lotteryStore.$state.isFriDollarBet) {
    costType.value = 2;
  }
});

// 关闭弹窗
const popupClose = () => {
  emit("update:show", false);
};

/************************* start 五组号码 start *************************/
/**
 * @description: 随机生成一个长度为 5 的字符串数组,要求每个元素的范围在 0~9 a~f
 * @param {*} arrayLength 要生成几组
 * @param {*} stringLength 每一组的长度
 * @return {*} [string]
 */

function randomStrArr(arrayLength: number, stringLength: number) {
  const characters = "0123456789abcdef";
  const uniqueStrings = new Set();

  while (uniqueStrings.size < arrayLength) {
    const str = Array.from(
      { length: stringLength },
      () => characters[Math.floor(Math.random() * characters.length)]
    ).join("");
    uniqueStrings.add(str);
  }

  return [...uniqueStrings];
}

const numbers5: any = ref([]); // 五组号码
let stepMax =
  Number(lotteryStore.$state.leftDrawCount) +
  Number(lotteryStore.$state.freeDrawCount); // 最多下注 50 + free 注
let bdcBetMax = Number(lotteryStore.$state.maxSessionDrawCount) || 50; // 最多下注50次

/**
 * @description: 添加几组号码; 1. 由于情况较多,切复杂,无需控制每组下注上限;点击下注在校验
 * @param {*} length 添加几组
 */
const addNumber = (length: number) => {
  if (numbers5.value.length >= 5) {
    return showToast({
      message: t("lotteryMoney.yczdxwz"),
      "z-index": 9999999,
    });
  }
  // 1.要生成几组
  const sycd = 5 - numbers5.value.length;
  let l = 0;
  if (length <= sycd) {
    l = length;
  } else if (length > sycd) {
    l = sycd;
  }

  if (l == 0) return;
  // 2. 生成号码
  const result = randomStrArr(l, 5);
  // 5. 组装数据
  result.forEach((e: any, index: number) => {
    numbers5.value.push({
      id: e,
      numArr: e.split(""), // 号码数组
      isManual: false, // 是否手动输入
      stepper: 1, // 多少注
      // stepMax: stepMax, // 上限 50 注
      stepMax: 999999, // 由于美金下注不限制下注数量,所以这里上限无穷大
    });
  });
};
/************************* start 批量下注 start *************************/
// 批量下注
const stepperBeforeChange = (index: any, val: any) => {
  // console.log("stepperBeforeChange value", val);
  // 0. 输入框清空了,重置为 0;焦点消失就会 stepperBeforeBlur 删除
  if (validatenull(val)) {
    numbers5.value[index].stepper = "";
    return true;
  }

  // 已经下注数量(不包含当前item 的数量)
  let alreadyBets = 0;
  numbers5.value.forEach((e: any, idx: number) => {
    if (index != idx) alreadyBets += Number(e.stepper);
  });
  // 剩余数量
  const sysl =
    Number(lotteryStore.$state.leftDrawCount) +
    Number(lotteryStore.$state.freeDrawCount) -
    alreadyBets;
  // console.log("剩余数量:", sysl);
  // 1. 增加注
  if (numbers5.value[index] && val - numbers5.value[index].stepper > 0) {
    // 1.1 刚好到达上限
    if (val == sysl) {
      return true;
    }
    // 1.2 小于上限,可以赋值
    else if (val < sysl) {
      return true;
    }
    // 1.3 大于上限
    else {
      // showToast({
      //   message: t("lotteryMoney.curBetLint"),
      //   "z-index": 9999999,
      // });
      return true;
    }
  }
  // 2. 减少注
  else if (numbers5.value[index] && val - numbers5.value[index].stepper < 0) {
    // 2.1 删除这一组号码
    if (val <= 0) {
      numbers5.value.splice(index, 1);
      return false;
    } else {
      return true;
    }
  }
};
// 步进器失去焦点
const stepperBeforeBlur = (index: number, val: any) => {
  // 删除这一组号码
  if (!numbers5.value[index].stepper || numbers5.value[index].stepper == 0) {
    numbers5.value.splice(index, 1);
  } else {
    /****** 美金下注无上限,以下代码,不能执行 ******/
    // 已经下注数量(不包含当前item 的数量)
    // let alreadyBets = 0;
    // numbers5.value.forEach((e: any, idx: number) => {
    //   if (index != idx) alreadyBets += Number(e.stepper);
    // });
    // const syxzsl =
    //   Number(lotteryStore.$state.leftDrawCount) +
    //   Number(lotteryStore.$state.freeDrawCount) -
    //   alreadyBets;
    // // 达到上限;设置上限
    // if (val.target._value > syxzsl) {
    //   let total = 0; // 不包含当前item 的总和
    //   numbers5.value.forEach((e: any, idx: number) => {
    //     if (index != idx) total += Number(e.stepper);
    //   });
    //   numbers5.value[index].stepper = stepMax - total > 0 ? stepMax - total : 1; // 这个判断是为了不设置 0,最低 1
    // }
  }
};
/************************* start 修改号码 start *************************/
const keyboardStrs = [
  ["a", "b", "c", "d", "e", "f"],
  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, t("common.confirm")],
];

const isKeyboardShow = ref(false); // 是否显示自定义键盘
const curSelectIndex = ref("");
// 点击号码
const clickNumItem = (row: number, col: number) => {
  curSelectIndex.value = `${row}${col}`;
  isKeyboardShow.value = true;
};

// 点击键盘
const keyboardClick = (idx: number, index: number) => {
  console.log('idx, index', idx, index);
  
  // 点击了:确认
  if (idx == 1 && index == 10) {
    isKeyboardShow.value = false;
    curSelectIndex.value = "";
  } else {
    // 获取键盘,字符
    const keyWord = keyboardStrs[idx][index];
    // 更新数据
    const indexArr = curSelectIndex.value.split("");
    if (!numbers5.value[Number(indexArr[0])]) {
      showToast({
        message: t("lotteryMoney.djhmqkxg"),
        "z-index": 9999999,
      });
      return;
    }
    numbers5.value[Number(indexArr[0])].numArr[Number(indexArr[1])] = keyWord;
    // 手动修改,告诉后端
    numbers5.value[Number(indexArr[0])].isManual = true;
    // 是否有下一位,有的话,继续更新下一位字符
    if (Number(indexArr[1]) < 4) {
      curSelectIndex.value = `${indexArr[0]}${Number(indexArr[1]) + 1}`;
    }
  }
};
/************************* start 立即下注 start *************************/
// 禁用状态
const isDisabled = computed(() => {
  if (step.value == 0) {
    return numbers5.value.length <= 0;
  } else if (step.value == 1) {
    if (costType.value == 1) {
      return Number(needPay.value) > Number(freeAmount.value);
    }
  }
  return false;
});

// 当前下注总数量
const betTotal = computed(() => {
  if (numbers5.value.length > 0) {
    let t = 0;
    numbers5.value.forEach((element: any) => {
      t += element.stepper;
    });
    return t;
  }
  return 0;
});

// 需要使用几张免费卷
const needFrees = computed(() => {
  let nums = 0;
  if (lotteryStore.$state.freeDrawCount <= betTotal.value) {
    nums = lotteryStore.$state.freeDrawCount;
  } else {
    nums = betTotal.value;
  }
  return nums;
});

// 需要支付多少美金/BDC
const needPay = computed(() => {
  if (costType.value == 1) {
    return new Decimal(betTotal.value - needFrees.value).mul(100);
  } else {
    return new Decimal(betTotal.value - needFrees.value).mul(0.1);
  }
});

/**
 * @description: 下注接口
 */
const lotteryBettingRequest = async () => {
  // 1. 使用 loading 遮罩
  showLoadingToast({
    message: `${t("common.requestIng")}...`,
    forbidClick: true,
    duration: 15000,
    zIndex: 999999999,
  });

  try {
    const res = await bettingBatchV3({
      sessionId: lotteryStore.$state.sessionId,
      totalBdcDrawCount:
        costType.value == 1 ? betTotal.value - needFrees.value : null, // BDC
      totalSecurityAccountDrawCount:
        costType.value == 2 ? betTotal.value - needFrees.value : null, // 美元
      totalFreeDrawCount: needFrees.value ? needFrees.value : null, // 免费券数量
      detailList: numbers5.value.map((e: any) => {
        return {
          drawNo: e.numArr.join(""),
          drawCount: e.stepper,
          drawType: e.isManual ? 1 : 2,
        };
      }),
    });

    console.log("下注成功:", res);

    // 1. 下注成功
    if (res) {
      emit("call", {
        type: 1,
        freeDrawCount: res.freeDrawCount,
        // sessionFreeDrawCount: res.sessionFreeDrawCount,
        leftDrawCount: res.leftDrawCount,
        orderNo: res.orderNo,
        numbers5: numbers5.value,
      });
      popupClose();
    }
    // 4. 下注失败
    else {
      popupClose();
      MITO.log({
        message: "下注失败: res 不存在",
        tag: "手动上报",
        level: "low",
        ex: "手动上报",
      });
    }
  } catch (error) {
    console.log("error", error);
    // 只要下注以后,都直接进入下注页面
    popupClose();
    emit("call", { type: 2 });
  }
};

// server后端,下注花费类型 1:BDC 2:美元; 周五,无资格只能是 2 美元下注
const costType = ref(1);
const costTypeChange = (type: number) => {
  // 有资格
  if (!lotteryStore.$state.isFriDollarBet) {
    costType.value = type;
  }
  // 无资格,点击 bdc
  else if (type == 1) {
    showToast({
      message: t("lotteryMoney.wzg"),
      "z-index": 9999999,
    });
  }
};
// 1. 选择号码 2. 结算
const confirm = debounce(
  (val: any) => {
    if (isDisabled.value) return;
    // 1. 选择号码
    if (val == 1) {
      // 1.1 校验,单次下注是否超过了 50 注
      let alreadyBets = 0;
      numbers5.value.forEach((e: any, idx: number) => {
        alreadyBets += Number(e.stepper);
      });
      if (alreadyBets > bdcBetMax) {
        return showToast({
          message: t("lotteryMoney.betDayLint").replace(
            "xxx",
            `${lotteryStore.$state.maxSessionDrawCount || 50}`
          ),
          "z-index": 9999999,
        });
      }
      // 1.2 跳转第二步骤
      swipeRef.value && swipeRef.value?.swipeTo(1);
      // 1.3 如果BDC 余额不足,默认选择美元支付
      nextTick(() => {
        if (
          costType.value == 1 &&
          Number(needPay.value) > Number(freeAmount.value)
        ) {
          costType.value = 2;
        }
      });
    }
    // 2. 结算
    else if (val == 2) {
      // BDC 结算
      if (costType.value == 1) {
        // 账户冻结
        if (accountStatus != 1) {
          showToast({
            message: t("lotteryMoney.bdczhyc"),
            "z-index": 9999999,
          });
        }
        // BDC下注每日最多50注
        else if (betTotal.value > stepMax) {
          showToast({
            message: t("lotteryMoney.bdcBetMaxcs").replace(
              "xxx",
              `${lotteryStore.$state.maxSessionDrawCount || 50}`
            ),
            "z-index": 9999999,
          });
        } else {
          lotteryBettingRequest();
        }
      }
      // 美元结算
      else {
        // 未获取到避险账户信息,不能继续下一步
        if (isBxzhStatus.value == -1) {
          getNewAccountInfoRequest();
        }
        // 未激活
        else if (isBxzhStatus.value == 0 || isBxzhStatus.value == 2) {
          swipeRef.value && swipeRef.value?.swipeTo(2);
        }
        // 余额不足
        else if (Number(needPay.value) > Number(accountBXInfo.value)) {
          isBxzhStatus.value = 3;
          swipeRef.value && swipeRef.value?.swipeTo(2);
        }
        // 下注
        else {
          lotteryBettingRequest();
        }
      }
    }
    // 去充值
    else if (val == 3) {
      // 桥接跳转到避险账户,目前安卓正在开发,暂时跳转到tabbar我的
      firebase?.logEvent("BDC_H5_lotteryv3_Click_HedgeAccount");
      const hedgingWallet = JUMPAPPS()["hedgingWallet"]();
      bridge.jumpAppRoute(
        hedgingWallet.routeKey,
        isAndroid.value,
        hedgingWallet
      );
      nextTick(() => {
        popupClose();
      });
    }
    // 去激活
    else if (val == 4) {
      // 激活-避险账户
      firebase?.logEvent("BDC_H5_lotteryv3_Click_HedgeAccount_jh");
      const hedgeAccount = JUMPAPPS()["hedgeAccount"]();
      bridge.jumpAppRoute(hedgeAccount.routeKey, isAndroid.value, hedgeAccount);

      nextTick(() => {
        popupClose();
      });
    }
  },
  500,
  false
);
</script>
<style lang="scss" scoped>
.box {
  // height: 495 * 2px;
  padding-bottom: var(--safe-area-inset-bottom);
  position: relative;
  flex-direction: column;
  justify-content: space-between;
  background: #fff;
  overflow: hidden;
  &-absolute {
    position: absolute;
    top: 0;
  }
}
.titlebg {
  position: relative;
  padding: 15 * 2px;

  &-text {
    width: 100vw;
    color: #141924;
    text-align: center;
    font-size: 15 * 2px;
    font-weight: 590;
  }
  &-close {
    position: absolute;
    top: 13 * 2px;
    right: 28 * 2px;
    width: 20 * 2px;
    height: 20 * 2px;
  }
}

.titleView {
  position: relative;
  width: 100vw;
  padding: 15 * 2px;
  justify-content: space-between;

  &-text {
    color: #141924;
    text-align: center;
    font-size: 15 * 2px;
    font-weight: 590;
  }
  &-close {
    width: 20 * 2px;
    height: 20 * 2px;
  }
}

.content {
  width: 100%;
  padding: 0 15 * 2px;
  flex-direction: column;
  justify-content: center;

  &-title {
    color: #999da7;
    font-size: 12 * 2px;
    font-weight: 400;
    margin: 8 * 2px 0;
  }
  &-add {
    display: inline-flex;
    margin: 11 * 2px 0;
    padding: 4 * 2px 10 * 2px;
    border-radius: 4 * 2px;
    background: linear-gradient(90deg, #007bff 0.07%, #00b2ff 99.93%);
    font-size: 13 * 2px;
    font-weight: 590;
    color: #fff;

    &-img {
      width: 12 * 2px;
      height: 12 * 2px;
      margin-right: 8 * 2px;
    }
  }
  &-list {
    width: 100%;
    min-height: 240 * 2px;
    flex-direction: column;
    // justify-content: space-between;

    &-item {
      justify-content: space-between;
      width: 100%;
      margin: 6 * 2px 0;

      &-bm0 {
        margin-bottom: 0 !important;
      }

      &-index {
        width: 18 * 2px;
        text-align: center;
        font-size: 13 * 2px;
        font-weight: 400;
        color: #999da7;
      }
      &-left {
        justify-content: space-between;

        &-input {
          width: 36 * 2px;
          height: 36 * 2px;
          line-height: 36 * 2px;
          text-align: center;
          border-radius: 100px;
          background: linear-gradient(90deg, #d9f3ff 0%, #d9ecff 54%);
          font-size: 15 * 2px;
          font-weight: 590;
          color: #002853;
          margin-left: 8 * 2px;

          &-activity {
            background: linear-gradient(90deg, #007bff 0%, #00b2ff 100%);
            color: #fff;
          }
        }
      }
      &-right {
        :deep(.van-stepper__minus:before) {
          height: 2 * 2px;
          border-radius: 100px;
        }

        :deep(.van-stepper__plus:before) {
          height: 2 * 2px;
          border-radius: 100px;
        }
        :deep(.van-stepper__plus:after) {
          width: 2 * 2px;
          border-radius: 100px;
        }

        :deep(.van-haptics-feedback) {
          background: #fff;
        }

        :deep(.van-stepper__input) {
          border-radius: 4 * 2px;
          color: #141924;
          font-size: 13 * 2px;
          font-weight: 590;
          width: 40 * 2px;
        }
      }
    }
  }

  &-settlements {
    width: 100%;
    min-height: 160 * 2px;
    flex-direction: column;
    justify-content: center;

    &-item {
      justify-content: space-between;
      width: 100%;
      padding: 4 * 2px 0;

      &-bm0 {
        margin-bottom: 0 !important;
      }

      &-index {
        width: 18 * 2px;
        text-align: center;
        font-size: 13 * 2px;
        font-weight: 400;
        color: #999da7;
        margin-right: 10 * 2px;
      }

      &-left {
        justify-content: space-between;

        &-input {
          position: relative;
          margin-left: 20 * 2px;
          &-text {
            position: relative;
            z-index: 2;
            width: 24 * 2px;
            height: 24 * 2px;
            line-height: 24 * 2px;
            text-align: center;
            font-size: 15 * 2px;
            font-weight: 590;
            color: #fff;
          }
          &-bg {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }
      }
      &-right {
        color: #141924;
        font-size: 13 * 2px;
        font-weight: 400;
      }
    }
    &-method {
      padding: 8 * 2px 0 6 * 2px 0;
      width: 100%;
      justify-content: space-between;

      &-item {
        position: relative;
        padding: 6 * 2px 2 * 2px;
        border-radius: 4 * 2px;
        background: #e5f2ff;
        width: 176 * 2px;
        height: 60 * 2px;

        justify-content: center;
        flex-direction: column;

        &-disabled {
          background: #f0f0f0;
        }

        &-title {
          text-align: center;
          font-size: 14 * 2px;
          font-weight: 590;
          color: #141924;
          margin-bottom: 2 * 2px;
          &-activity {
            color: #fff;
          }
          &-disabled {
            color: #999da7;
          }
        }

        &-value {
          text-align: center;
          font-size: 12 * 2px;
          font-weight: 400;
          color: #999da7;
          &-activity {
            color: rgba(255, 255, 255, 0.8);
          }

          &-disabled {
            color: #aaadb5;
          }
        }

        &-icon {
          position: absolute;
          z-index: 9;
          bottom: 0;
          right: 0;
          width: 22 * 2px;
          height: 22.5 * 2px;
        }

        &-activity {
          border: 0.5px solid #002853;
          background: linear-gradient(90deg, #01b2ff 0%, #0180ff 54.17%);
        }
      }
    }
  }

  &-random {
    padding: 10 * 2px 0;
    width: 100%;
    justify-content: space-between;

    &-item {
      width: calc((100% - 10 * 4px) / 3);
      text-align: center;
      font-size: 12 * 2px;
      font-weight: 590;
      color: #007bff;
      letter-spacing: -0.4px;
      padding: 6 * 2px 2 * 2px;
      border-radius: 4 * 2px;
      background: #e5f2ff;
    }
  }

  &-bottom {
    flex-direction: column;
    justify-content: space-evenly;
    margin: 6 * 2px 0;
    padding: 5 * 2px 10 * 2px;
    border-radius: 4 * 2px;
    border: 0.7px solid rgba(115, 119, 128, 0.15);
    width: 100%;
    min-height: 68 * 2px;

    &-item {
      width: 100%;
      justify-content: space-between;
      &-title {
        color: #999da7;
        font-size: 12 * 2px;
        font-weight: 400;
      }
      &-value {
        color: #141924;
        font-size: 12 * 2px;
        font-weight: 400;
      }
      &-line {
        height: 0.7px;
        width: 100%;
        margin: 4 * 2px 0;
        border-bottom: 0.7px solid rgba(115, 119, 128, 0.15);
      }
      &-right {
        &-icon {
          width: 18 * 2px;
          height: 13 * 2px;
          margin-right: 4 * 2px;
        }
        &-bdc {
          color: #ff4040;
          font-size: 12 * 2px;
          font-weight: 400;
          margin-left: 12 * 2px;
        }
      }
    }
  }

  &-footer {
    flex-direction: column;
    justify-content: space-around;
    min-height: 120 * 2px;
    width: 100%;
  }

  &-pay {
    justify-content: center;
    margin-bottom: 4 * 2px;
    padding: 2 * 2px 0;
    font-size: 13 * 2px;
    color: #141924;
    font-weight: 400;
    &-bm0 {
      margin-bottom: 0px;
    }
    &-value {
      color: #007bff !important;
    }
    &-yebz {
      justify-content: center;
      margin-bottom: 8 * 2px;
      &-icon {
        width: 18 * 2px;
        height: 18 * 2px;
        margin-right: 4 * 2px;
      }
      &-text {
        font-size: 12 * 2px;
        color: #ff4040;
        font-weight: 400;
      }
    }
  }

  &-abnormal {
    &-img {
      margin-top: 60 * 2px;
      width: 180 * 2px;
      height: 180 * 2px;
    }
    &-title {
      margin: 10 * 2px 0;
      font-size: 15 * 2px;
      font-weight: 590;
      color: #141924;
      text-align: center;
    }
    &-desc {
      text-align: center;
      font-size: 14 * 2px;
      font-weight: 400;
      color: #999da7;
      margin-bottom: 80 * 2px;
    }
  }
}

.footer {
  width: 100%;
  justify-content: center;
  padding: 6 * 2px 15 * 2px;
  // 提升高度，避免键盘遮挡
  &-up {
    margin-bottom: 20 * 2px;
  }

  &-btn {
    border-radius: 6 * 2px;
    background-color: #007bff;

    color: #fff;
    text-align: center;
    font-size: 15 * 2px;
    font-weight: 590;
    width: 100%;
    height: 44 * 2px;
    line-height: 44 * 2px;
    &-disabled {
      background-color: #a0ceff;
    }
    &-cancel {
      background-color: #fff;
      color: #007bff;
      border: 3px solid #007bff;
      margin-left: 10 * 2px;
    }
  }
}

.keyboard {
  position: fixed;
  justify-content: space-between;
  bottom: 0;
  z-index: 99;
  padding-bottom: calc(var(--safe-area-inset-bottom) + 10 * 2px);

  background: #bec8d3;
  &-row0 {
    width: 100%;
    justify-content: space-between;
    padding: 10 * 2px;
    background-color: #9eadbd;
  }

  &-row1 {
    padding: 10 * 2px;
    flex-wrap: wrap;
  }

  &-item {
    border-radius: 5 * 2px;
    background: #fff;
    box-shadow: 0px 2px 0px 0px rgba(0, 0, 0, 0.3);
    margin-right: 10 * 2px;
    min-width: 55 * 2px;
    height: 44 * 2px;
    line-height: 44 * 2px;
    font-size: 22 * 2px;
    font-weight: 400;
    color: #000;
    text-align: center;

    &-confirm {
      width: 118 * 2px;
      height: 44 * 2px;
      line-height: 44 * 2px;

      margin-right: 0px !important;
      font-size: 17 * 2px;
      font-weight: 400;
      color: #fff;
      text-align: center;
      border-radius: 5 * 2px;
      background: #007bff;
      box-shadow: 0px 2px 0px 0px rgba(0, 0, 0, 0.3);
    }

    &-bt18 {
      margin-top: 18 * 2px;
    }
    &-br0 {
      margin-right: 0 !important;
    }

    &-bm0 {
      margin-bottom: 0 !important;
    }
  }
}
</style>
